<?php
/**
 * oauth2验证
 */
namespace Common\qscmslib;
class oauth2 {
    protected $server;
    /**
     * 初始化
     */
    public function __construct() {
        $dsn      = 'mysql:dbname=oauth;host=localhost';
        $username = 'root';
        $password = 'hongker';
        
        require_once(__DIR__.'/OAuth2/Autoloader.php');
        \OAuth2\Autoloader::register();
        
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
        
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $this->server = new \OAuth2\Server($storage);
        
        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
        $this->server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));
        
        // Add the "Authorization Code" grant type (this is where the oauth magic happens)
        $this->server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));
    }
    
    /**
     * 发放token
     * 
     * 1.创建应用
     *   INSERT INTO oauth_clients (client_id, client_secret, redirect_uri) VALUES ("testclient", "testpass", "http://fake/");
     *   
     * 2.curl获取token
     *      curl -u testclient:testpass http://localhost/token.php -d 'grant_type=client_credentials'
     */
    public function token() {
        $this->server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
    }
    
    /**
     * 返回资源
     * 
     * curl http://localhost/resource.php -d 'access_token=YOUR_TOKEN'
     */
    public function resource() {
        if (!$this->server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
            $this->server->getResponse()->send();
            die;
        }
        echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
    }
}